﻿using AutoMapper;
using DFGK.IRepository;
using DFGK.IRepository.LY;
using DFGK.IService.BBS;
using DFGK.IService.LY;
using DFGK_WMS.Model.Models.LyModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DFGK.Service.LY
{
    public class PurchaseStandardService : BaseService, IPurchaseStandardService
    {
        private readonly IPurchaseStandardRepository _purchaseStandardRepository;
        private readonly IUnitOfWork _unitOfWork;
        public PurchaseStandardService(IMapper mapper, IPurchaseStandardRepository purchaseStandardRepository, IUnitOfWork unitOfWork) : base(mapper)
        {
            _purchaseStandardRepository = purchaseStandardRepository;
            _unitOfWork = unitOfWork;
        }
        public List<PurchaseStandard> GetPurchaseStandardPageData(string? name, out int totalCount, int pageIndex = 1, int pageSize = 20)
        {
           var list= _purchaseStandardRepository.GetEntityAlls();
            if (!string.IsNullOrEmpty(name))
            {
                list = list.Where(d => d.StandardName.Contains( name));
            }
            totalCount = list.Count();
            list = list.Skip((pageIndex - 1) * pageSize).Take(pageSize).OrderByDescending(d => d.Id);
            return list.ToList();
        }
        public bool DelPurchaseStandard(long purchaseStandardId)
        {
            var PurchaseStandard = _purchaseStandardRepository.QueryEntityById(purchaseStandardId);
            if (PurchaseStandard == null)
            {
                return false;
            }
            _purchaseStandardRepository.DelEntity(PurchaseStandard);
            return _unitOfWork.SaveChangesEntity();
        }

        public bool AddPurchase(List<PurchaseStandard> list)
        {
            int count = 0;
            foreach (var purchase in list)
            {
                _purchaseStandardRepository.AddEntity(purchase);
                _unitOfWork.SaveChangesEntity();
                count++;
            }
            if(count <= 0)
            {
                return false;
            }
            return true;
            
        }
        public PurchaseStandard? GetPurchaseStandard(long purchaseStandardId)
        {
            return _purchaseStandardRepository.QueryEntityById(purchaseStandardId);

        }

        public List<PurchaseStandard> GetPurchaseStandardPageDown()
        {
            var pur = _purchaseStandardRepository.GetAllEntityList();
            return pur;
        }

        public bool PurchaseStandardData(PurchaseStandard model, out string errorMsg)
        {
            errorMsg=string.Empty;
            if(model.Id > 0)
            {
                _purchaseStandardRepository.UpdEntity(model);
            }
            else
            {
                _purchaseStandardRepository.AddEntity(model);
            }
            return _unitOfWork.SaveChangesEntity();
        }
    }
}
